package io.wongxd.demo.page

import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.lifecycleScope
import io.wongxd.demo.AppBtn
import io.wongxd.demo.V
import io.wongxd.solution.baseView.BaseComposeToolBarFgt
import io.wongxd.solution.permissionFlow.MultiplePermissionState
import io.wongxd.solution.permissionFlow.PermissionFlow
import io.wongxd.solution.permissionFlow.initializer.PermissionFlowInitializer
import io.wongxd.solution.permissionFlow.utils.registerForPermissionFlowRequestsResult
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach

class FgtPermissionFlow : BaseComposeToolBarFgt() {
    override fun lazyInit() {
        observePermissions()
    }

    private val permissionFlow = PermissionFlow.getInstance()

    private val permissionLauncher = registerForPermissionFlowRequestsResult()

    private val permissions = arrayOf(
        android.Manifest.permission.CAMERA,
        android.Manifest.permission.ACCESS_COARSE_LOCATION,
        android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
        android.Manifest.permission.READ_EXTERNAL_STORAGE,
        android.Manifest.permission.READ_CALL_LOG,
        android.Manifest.permission.READ_CONTACTS,
        android.Manifest.permission.READ_PHONE_STATE,
    )

    private fun observePermissions() {
        permissionFlow.getMultiplePermissionState(*permissions) // or use `getPermissionState()` for observing a single permission

            .onEach { onPermissionStateChange(it) }
            .launchIn(lifecycleScope)
    }

    private fun onPermissionStateChange(state: MultiplePermissionState) {
        if (state.allGranted) {
            "All permissions are granted!".showToast()
        }

        granted.value =
            "Granted permissions: ${state.grantedPermissions.joinToStringByNewLine()}"

        denied.value =
            "Denied permissions: ${state.deniedPermissions.joinToStringByNewLine()}"
    }

    private fun List<String>.joinToStringByNewLine(): String {
        return joinToString(prefix = "\n", postfix = "\n", separator = ",\n")
    }

    private val granted = mutableStateOf("")
    private val denied = mutableStateOf("")

    @Composable
    override fun Render() {
        Column(Modifier) {
            V(number = 20)

            Text(text = granted.value)

            V(number = 20)

            Text(text = denied.value)

            V(number = 20)

            AppBtn(text = "请求权限") {
                permissionLauncher.launch(permissions)
            }
        }
    }

    @Preview(showBackground = true, backgroundColor = 0xffffffff)
    @Composable
    fun RenderPreView() {

    }
}